package com.ruitu.health_1.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.Gson;
import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.CalcUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.health_1.R;
import com.ruitu.health_1.mvp.model.ShoppingCartModel;
import com.ruitu.health_1.mvp.presenter.ShoppingCartPresenter;
import com.ruitu.health_1.ui.CommitOrderActivity;
import com.ruitu.health_1.util.CustomDialogUtil;
import com.ruitu.health_1.util.CustomInterface;
import com.ruitu.health_1.view.AmountView;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.Router;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.cart.Cart;
import com.ruitu.router_module.bean.cart.OmsCartItemListBean;
import com.ruitu.router_module.bean.order.ConfirmOrder;
import com.ruitu.router_module.bean.product.ProHome;
import com.ruitu.router_module.bean.product.Sku;
import com.ruitu.router_module.support.widget.ProductSkuDialog;
import com.ruitu.router_module.util.ReqUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShoppingCartFragment extends BaseFragment<ShoppingCartPresenter.ShoppingCartP, ShoppingCartModel.ShoppingCartM> {
    public static ShoppingCartFragment newInstance() {

        Bundle args = new Bundle();

        ShoppingCartFragment fragment = new ShoppingCartFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private LRecyclerView l_recyclerview;
    private RelativeLayout rl_buttom;
    private LinearLayout view_empty;
    private TextView tv_settlement;
    private TextView tv_delete;
    private TextView tv_total;
    private CheckBox cb_check_all;
    private LRecyclerViewAdapter lRecyclerViewAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Arad.bus.register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shoping_cat, container, false);
        l_recyclerview = view.findViewById(R.id.l_recyclerview);
        rl_buttom = view.findViewById(R.id.rl_buttom);
        view_empty = view.findViewById(R.id.view_empty);
        tv_settlement = view.findViewById(R.id.tv_settlement);
        tv_delete = view.findViewById(R.id.tv_delete);
        tv_total = view.findViewById(R.id.tv_total);
        cb_check_all = view.findViewById(R.id.cb_check_all);
        Context context = getContext();
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        adapter = new StoreAdapter(context);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        l_recyclerview.setLayoutManager(layoutManager);
        l_recyclerview.setAdapter(lRecyclerViewAdapter);
        setListener();

        judge();
        return view;
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (cb_check_all == view) {
            boolean checked = cb_check_all.isChecked();
            for (int i = 0; i < cartList.size(); i++) {
                List<OmsCartItemListBean> omsCartItemList = cartList.get(i).getOmsCartItemList();
                cartList.get(i).setStoreCheck(checked);
                for (int j = 0; j < omsCartItemList.size(); j++) {
                    cartList.get(i).getOmsCartItemList().get(j).setCheck(checked);
                }
            }
            setAll();
            adapter.setDataList(cartList);
        }
        if (tv_settlement == view) {
            if (!isSettlementCheck()) {
                ToastUtils.showShort("请选择结算的商品");
                return;
            }

            setSettlement(map);
        }

        if (tv_delete == view) {
            selectDel();
        }
    }

    private boolean isSettlementCheck() {
        for (Cart cart : cartList) {
            for (OmsCartItemListBean cartItemListBean : cart.getOmsCartItemList()) {
                if (cartItemListBean.isCheck()) {
                    return true;
                }
            }
        }
        return false;
    }

    private List<String> ids;
    private Map<String, String> map;
    private Gson gson;
    private String userId;
    private CustomDialogUtil dialog;

    private void setListener() {
        setOnClickListener(tv_settlement, cb_check_all, tv_delete);
        l_recyclerview.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                judge();
            }
        });

    }

    //选择删除
    private void selectDel() {
        dialog = new CustomDialogUtil(getContext(), "确认删除选中的" + ids.size() + "件商品?", new CustomInterface.OnBtnClickListener() {
            @Override
            public void onLeftClick() {
                map = new HashMap();
                gson = new Gson();
                String idsJson = gson.toJson(ids);
                map.put("ids", idsJson);
                map.put("memberId", userId);
                showProgress();
                p.deleteCart(ReqUtil.getBody(map, true));
            }

            @Override
            public void onRightClick() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void setAll() {
        cb_check_all.setChecked(isCheckedAll());
        setTotal();
    }

    //全选
    private boolean isCheckedAll() {
        for (Cart cartBean : cartList) {
            if (!cartBean.isStoreCheck()) {
                return false;
            }
        }
        return true;
    }

    //店铺全选
    private boolean isStoreCheckAll() {
        for (OmsCartItemListBean omsCartItemListBean : omsCartItemList) {
            if (!omsCartItemListBean.isCheck()) {
                return false;
            }
        }
        return true;
    }

    private List<String> getIds() {
        ids = new ArrayList<>();
        for (int i = 0; i < cartList.size(); i++) {
            Cart cart = cartList.get(i);
            for (int j = 0; j < cartList.get(i).getOmsCartItemList().size(); j++) {
                OmsCartItemListBean omsCartItemListBean = cart.getOmsCartItemList().get(j);
                if (omsCartItemListBean.isCheck()) {
                    ids.add(omsCartItemListBean.getId());
                }
            }
        }
        return ids;
    }

    //去结算
    private void setSettlement(Map map) {
        showProgress();
        p.settlement(ReqUtil.getBody(map, true));
    }

    private List<Sku> skus;

    //获取sku回调
    public void getSkuList(List<Sku> skuList) {
        this.skus = skuList;
        if (!isDataEmpty(skuList)) {
            showSkuDialog();
        }
    }

    //修改sku回调
    public void updateSuc() {
        skuDialog.dismiss();
        judge();
    }

    private ProductSkuDialog skuDialog;

    //选择商品属性
    private void showSkuDialog() {
        skuDialog = new ProductSkuDialog(getContext(), true);
        skuDialog.setData(proHome, skus, new ProductSkuDialog.Callback() {
            @Override
            public void onAdded(com.wuhenzhizao.sku.bean.Sku sku, int quantity) {
                Map<String, String> map = new HashMap<>();
                map.put("cartItemId", cartId);
                map.put("productSkuId", sku.getId());
                p.updateSku(ReqUtil.getBody(map, true));
            }
        });
        skuDialog.show();
    }

    private void setNum() {
        int amount = 0;
        List<OmsCartItemListBean> cartPromotionItemList = confirmOrder.getCartPromotionItemList();
        Logg.i("settlementData:" + cartPromotionItemList.toString());
        for (int i = 0; i < cartPromotionItemList.size(); i++) {
            OmsCartItemListBean cart = cartPromotionItemList.get(i);
            amount = amount + cart.getQuantity();

        }
        tv_settlement.setText("去结算" + "(" + amount + ")");
        tv_total.setText("合计:  ￥" + confirmOrder.getCalcAmount().getTotalAmount());
    }


    //计算价格和数量
    private void setTotal() {
        int q = 0;
        double pruTotal = 0;
        for (int i = 0; i < cartList.size(); i++) {
            Cart cart = cartList.get(i);
            for (int j = 0; j < cartList.get(i).getOmsCartItemList().size(); j++) {
                OmsCartItemListBean omsCartItemListBean = cart.getOmsCartItemList().get(j);
                if (omsCartItemListBean.isCheck()) {
//                    omsCartItemListBean.getPrice()
                    double m = CalcUtils.multiply(omsCartItemListBean.getPrice(), omsCartItemListBean.getQuantity());
                    pruTotal = CalcUtils.add(pruTotal, m);
                    q = q + omsCartItemListBean.getQuantity();
                }
            }
        }

        map = new HashMap<>();
        gson = new Gson();
        map.put("memberId", userId);
        map.put("ids", gson.toJson(getIds()));
        if (isDataEmpty(getIds())) {
            tv_settlement.setText("结算(0)");
            tv_total.setText("合计:  ￥ 0.0");
            tv_delete.setVisibility(View.GONE);
        } else {
            tv_settlement.setText("结算(" + q + ")");
            tv_total.setText("合计:  ￥ " + pruTotal);
            tv_delete.setVisibility(View.VISIBLE);
        }
    }


    private List<Cart> cartList;

    public void setData(List<Cart> carts) {
        cartList = carts;
        l_recyclerview.refreshComplete(20);
        adapter.setDataList(carts);
        if (isDataEmpty(cartList)) {
            rl_buttom.setVisibility(View.GONE);
            view_empty.setVisibility(View.VISIBLE);
            l_recyclerview.setVisibility(View.GONE);
        } else {
            rl_buttom.setVisibility(View.VISIBLE);
            view_empty.setVisibility(View.GONE);
            l_recyclerview.setVisibility(View.VISIBLE);
        }
        setAll();
    }

    private ConfirmOrder confirmOrder;

    //结算
    public void setSettlement(ConfirmOrder order) {
        this.confirmOrder = order;
//        setNum();
        Bundle bundle = new Bundle();
        bundle.putSerializable("order", confirmOrder);
        startActivity(CommitOrderActivity.class, bundle);
    }

    public void deleteSuc() {
        judge();
        dialog.dismiss();
    }

    public void changeSuc() {
        judge();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Arad.bus.unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setE(EventModel e) {
        if (e.getEventCode() == 19122300) {
            judge();
        }
    }

    private void judge() {
        if (CommonUtils.isLogin()) {
            userId = AppHolder.instance().getUser().getId();
            p.cartList(userId);
        }
    }

    private StoreAdapter adapter;

    private ProHome proHome;
    private String cartId;

    private List<OmsCartItemListBean> omsCartItemList;

    class StoreAdapter extends ListBaseAdapter<Cart> {

        public StoreAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_store_name;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_store_name = holder.getView(R.id.tv_store_name);
            RecyclerView recyclerView = holder.getView(R.id.l_recyclerview);
            ImageView cb_store_check = holder.getView(R.id.cb_store_check);
            final Cart cart = mDataList.get(position);
            tv_store_name.setText(cart.getName());
            LinearLayoutManager manager = new LinearLayoutManager(mContext);
            recyclerView.setLayoutManager(manager);
            omsCartItemList = cart.getOmsCartItemList();
            final boolean storeCheck = cart.isStoreCheck();
            if (storeCheck) {
                cb_store_check.setImageResource(R.mipmap.all_selects);
            } else {
                cb_store_check.setImageResource(R.mipmap.all_noselects);
            }
            cb_store_check.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    omsCartItemList = cartList.get(position).getOmsCartItemList();
                    if (storeCheck) {
                        for (int i = 0; i < omsCartItemList.size(); i++) {
                            cartList.get(position).setStoreCheck(false);
                            cartList.get(position).getOmsCartItemList().get(i).setCheck(false);
                        }
                    } else {
                        for (int i = 0; i < omsCartItemList.size(); i++) {
                            cartList.get(position).setStoreCheck(true);
                            cartList.get(position).getOmsCartItemList().get(i).setCheck(true);
                        }
                    }
                    setAll();
                    notifyDataSetChanged();
                }
            });
            DataAdapter adapter = new DataAdapter(mContext, position);
            recyclerView.setAdapter(adapter);

            adapter.setDataList(omsCartItemList);
        }
    }

    class DataAdapter extends ListBaseAdapter<OmsCartItemListBean> {
        public int sPosition;

        public DataAdapter(Context context, int position) {
            super(context);
            this.sPosition = position;
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_cat_shopping;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            final OmsCartItemListBean cart = mDataList.get(position);
            ImageView iv_product_img = holder.getView(R.id.iv_product_img);
            final ImageView cb_radio = holder.getView(R.id.tv_radio);
            TextView tv_product_name = holder.getView(R.id.tv_product_name);
            TextView tv_price = holder.getView(R.id.tv_price);
            TextView tv_sku_info = holder.getView(R.id.tv_sku_info);
            AmountView amount = holder.getView(R.id.amount);
            LinearLayout ll_item = holder.getView(R.id.ll_item);
            Glide.with(mContext).load(cart.getProductPic()).apply(Arad.opts).into(iv_product_img);
            StringBuffer buffer = new StringBuffer();
            if (!TextUtils.isEmpty(cart.getSp1())) {
                buffer.append(cart.getSp1());
            }
            if (!TextUtils.isEmpty(cart.getSp2())) {
                buffer.append("," + cart.getSp2());
            }
            if (!TextUtils.isEmpty(cart.getSp3())) {
                buffer.append("," + cart.getSp3());
            }

            tv_sku_info.setText(buffer.toString());
            tv_sku_info.setVisibility(TextUtils.isEmpty(buffer.toString()) ? View.GONE : View.VISIBLE);
            if (cart.isCheck()) {
                cb_radio.setImageResource(R.mipmap.all_selects);
            } else {
                cb_radio.setImageResource(R.mipmap.all_noselects);
            }
            cb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    omsCartItemList = mDataList;
                    if (cart.isCheck()) {
                        cartList.get(sPosition).getOmsCartItemList().get(position).setCheck(false);
                    } else {
                        cartList.get(sPosition).getOmsCartItemList().get(position).setCheck(true);
                    }
                    cartList.get(sPosition).setStoreCheck(isStoreCheckAll());
                    adapter.notifyDataSetChanged();
                    setAll();

                }
            });
            ll_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", cart.getProductId());
                    try {
                        Router.startActivity(mContext, "com.ruitu.health_2.ui.activity.ProductDetailActivity", bundle);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
            ll_item.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    dialog = new CustomDialogUtil(getContext(), "是否删除该商品?", new CustomInterface.OnBtnClickListener() {
                        @Override
                        public void onLeftClick() {
                            map = new HashMap();
                            gson = new Gson();
                            ids = new ArrayList<>();
                            ids.add(cart.getId());
                            String idsJson = gson.toJson(ids);

                            map.put("ids", idsJson);
                            map.put("memberId", userId);
                            showProgress();
                            p.deleteCart(ReqUtil.getBody(map, true));
                        }

                        @Override
                        public void onRightClick() {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                    return false;
                }
            });
            amount.setTextSize(10, 12);
            amount.setGoods_storage(999);
            tv_product_name.setText(cart.getProductSubTitle());
            tv_price.setText(span("￥  " + cart.getPrice()));
            amount.setAmounts(cart.getQuantity());

            amount.setOnAmountChangeListener(new AmountView.OnAmountChangeListener() {
                @Override
                public void onAmountChange(View view, int amount) {
                    Map<String, String> map = new HashMap<>();
                    map.put("cartItemId", cart.getId());
                    map.put("quantity", amount + "");
                    map.put("memberId", AppHolder.instance().getUser().getId());
                    showProgress();
                    p.changeQuantity(ReqUtil.getBody(map, true));
                }
            });
            tv_sku_info.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cartId = cart.getId();
                    proHome = new ProHome();

                    proHome.setPic(cart.getProductPic());
                    proHome.setStock("");
                    proHome.setUnit("");
                    proHome.setPic("" + cart.getPrice());
                    showProgress();
                    p.getProduct(cart.getProductId());
                }
            });
        }

    }

    private SpannableString span(String value) {
        SpannableString spannableString = new SpannableString(value);
        spannableString.setSpan(new RelativeSizeSpan(0.7f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }
}
